"""Header_Information
------------------------------------
    File_Name: mian.py
    Author: RR9
    Date: 2024/09/18
    Description: 应用主入库文件
------------------------------------
"""
# import fastapi_cdn_host
from fastapi import FastAPI, Depends
from fastapi.exceptions import RequestValidationError

from app.api.v1.endpoints.tutorial import tutorial, demo_tortoise
from app.api.v1.endpoints.ob1 import student, login, auth
from app.api.v2.endpoints import login as login_v2
from app.api.v2.endpoints import crud_01, tortoise_demo
from app.exception.exceptions_handlers import custom_validation_exception_handler

# tortoise
from tortoise.contrib.fastapi import register_tortoise
# 配置文件
from app.core.config import TORTOISE_ORM
# 依赖性
# Tortoise-ORM 全局管理事物依赖
from app.dependencies.core import transaction_manager_tortoise
# 中间件
from app.middlewares.loggingmiddleware import LoggingMiddleware

# 日志
from loguru import logger
from app.logging.config import add_module_logger

# 初始化并注册全局依赖等相关
# app = FastAPI()
app = FastAPI(
    dependencies=[Depends(transaction_manager_tortoise), ]
)
# ⚠️：网络不行的情况下，使用本地css,js文件
# 使用本地 swagger-ui.css 和 swagger-ui-bundle.js
# fastapi_cdn_host.patch_docs(app)

# 注册tortoise
register_tortoise(
    app=app,
    config=TORTOISE_ORM,
)

# 路由
# app.include_router(tutorial.router, prefix="/v1/tutorial", tags=['基础教程'])
# app.include_router(demo_tortoise.router, prefix="/v1/tutorial/tortoise", tags=['tortoise教程'])
# app.include_router(student.router, prefix="/v1/student", tags=['学生信息'])
# app.include_router(login.router, prefix="/v1", tags=['用户登录'])
# app.include_router(auth.router, prefix="/v1", tags=['权限认证'])
app.include_router(login_v2.router, prefix="/v2", tags=['登录'])
app.include_router(crud_01.router, prefix="/v2", tags=['crud_01'])
app.include_router(tortoise_demo.router, prefix="/v2/tortoise_demo", tags=['tortoise示例'])

# 异常
# 自定义异常处理器#
# 覆盖默认请求校验异常, 添加请求体数据
app.add_exception_handler(RequestValidationError, custom_validation_exception_handler)

# 中间件
app.add_middleware(LoggingMiddleware)


# 事件： 启动-关闭
# 项目启动前
@app.on_event("startup")
def startup_event():
    # 创建全局log
    log = add_module_logger('app', 'logs/app.log')
    log.info(f"Application程序开始...")


# 项目关闭前
@app.on_event("shutdown")
def shutdown_event():
    log = logger.bind(module='app')
    log.info(f"Application程序结束...")
